package com.gexin.controller.xapp;


import com.gexin.common.GeXinSessionKit;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.xapp.WxaConfigKit;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.kit.EmojiUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.wxaapp.api.WxaUserApi;

/**
 * 小程序登陆
 *
 * @author 黎峻
 */
@ControllerBind(controllerKey = "/xapp/login")
public class XAppLoginController extends AppController {
	private static Log log = Log.getLog(XAppLoginController.class);
	// 微信用户接口api
	protected WxaUserApi wxaUserApi = Duang.duang(WxaUserApi.class);

	public void v2() {
		//WxaConfigKit.setThreadLocalAppid(getWxappId());
		com.jfinal.wxaapp.WxaConfigKit.setWxaConfig(getWxaConfig());
		String jsCode = getPara("code");
		if (StrKit.isBlank(jsCode)) {
			renderJson(new ApiResponse(false, "code is blank"));
			return;
		}
		// 获取SessionKey
		ApiResult apiResult = wxaUserApi.getSessionKey(jsCode);
		if (!apiResult.isSucceed()) {
			log.error("用户登录接口请求失败:" + apiResult.getJson());
			renderJson(new ApiResponse(false, apiResult.getJson()));
			return;
		}
		log.info("apiResult:" + apiResult.getJson());
		// 利用 appId 与 accessToken 建立关联，支持多账户
		String sessionId = GeXinSessionKit.setSession(apiResult.getJson());
		renderJson(new ApiResponse(true, "success", sessionId));
	}

	public void index() {
		//WxaConfigKit.setThreadLocalAppid(getWxappId());
		com.jfinal.wxaapp.WxaConfigKit.setWxaConfig(getWxaConfig());
		String jsCode = getPara("code");
		if (StrKit.isBlank(jsCode)) {
			renderJson(new ApiResponse(false, "code is blank"));
			return;
		}
		// 获取SessionKey
		ApiResult apiResult = wxaUserApi.getSessionKey(jsCode);
		if (!apiResult.isSucceed()) {
			log.error("用户登录接口请求失败:" + apiResult.getJson());
			renderJson(apiResult.getJson());
			return;
		}
		log.info("apiResult:" + apiResult.getJson());
		// 利用 appId 与 accessToken 建立关联，支持多账户
		String sessionId = GeXinSessionKit.setSession(apiResult.getJson());
		renderJson("sessionId", sessionId);
	}

	/**
	 * 服务端解密用户信息接口 获取unionId
	 */
	@Before(XAppSafeInterceptor.class)//统一错误拦截
	public void getUserInfor() {
		com.jfinal.wxaapp.WxaConfigKit.setWxaConfig(getWxaConfig());
		//WxaConfigKit.setThreadLocalAppid(getWxappId());
		// JSONObject json = getRequestData();
		String signature = getPara("signature");
		String rawData = getPara("rawData");
		String encryptedData = getPara("encryptedData");
		log.info("encryptedData:" + encryptedData);
		String iv = getPara("iv");
		String sessionId = getAttr("user-token");
		log.info("start begin getUserInfor   : " + sessionId);
		// 参数空校验
		if (StrKit.isBlank(signature)) {
			log.error("getUserInfor  : signature参数不能为空！");
			renderJson(new ApiResponse(false, "signature参数不能为空！"));
			return;
		}
		if (StrKit.isBlank(rawData)) {
			log.error("getUserInfor  :  rawData参数不能为空！");
			renderJson(new ApiResponse(false, "rawData参数不能为空！"));
			return;
		}
		if (StrKit.isBlank(encryptedData)) {
			log.error("getUserInfor  : encryptedData参数不能为空！");
			renderJson(new ApiResponse(false, "encryptedData参数不能为空！"));
			return;
		}
		if (StrKit.isBlank(iv)) {
			log.error("getUserInfor  : iv参数不能为空！");
			renderJson(new ApiResponse(false, "iv参数不能为空！"));
			return;
		}

		if (StrKit.isBlank(sessionId)) {
			log.error("getUserInfor  : sessionid参数不能为空！");
			renderJson(new ApiResponse(false, "sessionid参数不能为空！"));
			return;
		}

		// 利用 appId 与 accessToken 建立关联，支持多账户
		// IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();

		String sessionJson = GeXinSessionKit.getSession(sessionId);
		if (StrKit.isBlank(sessionJson)) {
			log.error("getUserInfor  : 会话已过期！");
			ApiResponse resp = new ApiResponse(false, "会话已过期！");
			resp.setCode(102);//设置code 102 重新登录
			renderJson(resp);
			return;
		}
		ApiResult sessionResult = ApiResult.create(sessionJson);
		// 获取sessionKey
		String sessionKey = sessionResult.get("session_key");
		if (StrKit.isBlank(sessionKey)) {
			log.info("getUserInfor  : sessionKey为空！");
			renderJson(new ApiResponse(false, "sessionKey为空！"));
			return;
		}
		// 用户信息校验
		boolean check = wxaUserApi.checkUserInfo(sessionKey, rawData, signature);
		if (!check) {
			log.error("getUserInfor  : 用户信息校验失败,sessionKey:"+sessionKey+"   rawData:"+rawData+ "   signature:"+signature);
			GeXinSessionKit.delSession(sessionId);
			renderJson(new ApiResponse(false, "用户信息校验失败！"));
			return;
		}
		// 服务端解密用户信息
		log.info("用户信息 sessionKey：" + sessionKey);
		log.info("用户信息 encryptedData：" + encryptedData);
		log.info("用户信息 iv：" + iv);
		ApiResult apiResult = wxaUserApi.getUserInfo(sessionKey, encryptedData, iv);
		log.info("用户信息 返回结果：" + JsonKit.toJson(apiResult));
		log.info("getUserInfor  : 获取用户信息：" + apiResult.getJson());
		if (!apiResult.isSucceed()) {
			renderJson(apiResult.getJson());
			return;
		}

		WeixinUser wxuser = new WeixinUser();
		String unionId = apiResult.get("unionId");
		String openId = apiResult.get("openId");
		String nickName = EmojiUtils.emojiChange(apiResult.get("nickName"));
		Integer gender = apiResult.get("gender");
		String city = apiResult.get("city");
		String province = apiResult.get("province");
		String country = apiResult.get("country");
		String avatarUrl = apiResult.get("avatarUrl");
		WeixinUser user = WeixinUser.dao.getUserByOpentId(openId);
		if (user != null) {
			wxuser.setOpenid(openId);
			wxuser.setCity(city);
			wxuser.setUnionid(unionId);
			wxuser.setProvince(province);
			wxuser.setCountry(country);
			wxuser.setHeadimgurl(avatarUrl);
			wxuser.setXappid(apiResult.getMap("watermark").get("appid").toString());// 获取对应appid
			wxuser.setId(user.getId());
			wxuser.update();
		} else {
			wxuser.setOpenid(openId);
			wxuser.setNickname(nickName);
			wxuser.setSex(gender);
			wxuser.setCity(city);
			wxuser.setUnionid(unionId);
			wxuser.setProvince(province);
			wxuser.setCountry(country);
			wxuser.setHeadimgurl(avatarUrl);
			wxuser.setXappid(apiResult.getMap("watermark").get("appid").toString());// 获取对应appid
			wxuser.save();
		}
		renderJson(new ApiResponse(true, "解密用户信息成功！", wxuser));
	}
}
